/*
 * @Author: Kiro AI Assistant
 * @Date: 2025-01-10
 * @Description: 音乐搜索 ViewModel - 处理音乐搜索业务逻辑
 * 迁移自 MusicSearchVm，使用 MVVM 架构和 Provider 状态管理
 */

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'base_network_view_model.dart';
import '../models/music_item_model.dart';
import '../models/page_state.dart';
import '../services/music_api_service.dart';
import '../utils/error_handler.dart';

/// 搜索项数据模型
class SearchItem {
  final String text;
  final String? subtitle;

  const SearchItem({
    required this.text,
    this.subtitle,
  });

  factory SearchItem.fromJson(Map<String, dynamic> json) {
    return SearchItem(
      text: json['text'] ?? '',
      subtitle: json['subtitle'],
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'text': text,
      'subtitle': subtitle,
    };
  }

  @override
  bool operator ==(Object other) {
    if (identical(this, other)) return true;
    return other is SearchItem && other.text == text;
  }

  @override
  int get hashCode => text.hashCode;
}

/// 音乐搜索 ViewModel
/// 提供音乐搜索、分页加载、搜索历史管理等功能
class MusicSearchViewModel extends BaseNetworkViewModel {
  final MusicApiService _apiService = MusicApiService();

  // 搜索结果数据
  List<MusicItemModel> _searchList = [];
  List<MusicItemModel> _searchCanPlayList = [];
  List<MusicItemModel> _pageList = [];

  // 搜索状态
  String _currentQuery = '';
  int _currentPage = 1;
  bool _hasMore = true;

  // 搜索历史
  List<SearchItem> _historyItems = [];

  // 热门搜索（可配置）
  List<SearchItem> _hotItems = [
    const SearchItem(text: "郭德纲"),
    const SearchItem(text: "将光芒洒落大地"),
    const SearchItem(text: "小村庄月弯弯"),
    const SearchItem(text: "莫等风来"),
  ];

  // Getters
  List<MusicItemModel> get searchList => List.unmodifiable(_searchList);
  List<MusicItemModel> get searchCanPlayList =>
      List.unmodifiable(_searchCanPlayList);
  List<MusicItemModel> get pageList => List.unmodifiable(_pageList);
  String get currentQuery => _currentQuery;
  int get currentPage => _currentPage;
  bool get hasMore => _hasMore;
  List<SearchItem> get historyItems => List.unmodifiable(_historyItems);
  List<SearchItem> get hotItems => List.unmodifiable(_hotItems);

  /// 初始化 ViewModel
  @override
  void init() {
    super.init();
    _loadHistoryItems();
  }

  /// 搜索音乐
  /// [query] 搜索关键词
  /// [page] 页码，默认为1（新搜索）
  /// [isRefresh] 是否为刷新操作
  Future<void> search({
    required String query,
    int page = 1,
    bool isRefresh = false,
  }) async {
    if (query.trim().isEmpty) {
      setError('搜索关键词不能为空');
      return;
    }

    try {
      // 如果是新搜索，重置状态
      if (page == 1 || isRefresh) {
        _currentQuery = query.trim();
        _currentPage = 1;
        _hasMore = true;
        _searchList.clear();
        _searchCanPlayList.clear();
        _pageList.clear();

        // 保存搜索历史
        await _saveSearchHistory(SearchItem(text: _currentQuery));
      }

      setLoading();

      // 调用搜索API
      final results = await _apiService.loadSearchData(
        keyword: _currentQuery,
        page: page,
      );

      // 处理搜索结果
      await _processSearchResults(results, page);

      // 更新页面状态
      _updatePageState();

      if (page == 1 || isRefresh) {
        debugPrint('🔍 搜索完成: $_currentQuery, 结果数量: ${_searchList.length}');
      } else {
        debugPrint('📄 加载更多完成: 页码 $page, 新增结果: ${results.length}');
      }
    } catch (error, stackTrace) {
      setError('搜索失败: ${error.toString()}');
      ErrorHandler.handleError(error, stackTrace);
    }
  }

  /// 加载更多搜索结果
  Future<void> loadMore() async {
    if (!_hasMore || state == PageState.loading) {
      return;
    }

    if (_currentQuery.isEmpty) {
      return;
    }

    await search(
      query: _currentQuery,
      page: _currentPage + 1,
    );
  }

  /// 刷新搜索结果
  Future<void> refresh() async {
    if (_currentQuery.isEmpty) {
      return;
    }

    await search(
      query: _currentQuery,
      page: 1,
      isRefresh: true,
    );
  }

  /// 处理搜索结果
  /// [results] API返回的搜索结果
  /// [page] 当前页码
  Future<void> _processSearchResults(
      List<MusicItemModel> results, int page) async {
    final List<MusicItemModel> processedResults = [];
    final List<MusicItemModel> playableResults = [];

    for (final item in results) {
      // 处理高亮文本（如果API返回了高亮信息）
      final processedItem = await _processHighlightText(item);
      processedResults.add(processedItem);

      // 过滤可播放的音乐
      if (!processedItem.disabled) {
        playableResults.add(processedItem);
      }
    }

    // 更新数据
    if (page == 1) {
      _searchList = processedResults;
      _searchCanPlayList = playableResults;
    } else {
      _searchList.addAll(processedResults);
      _searchCanPlayList.addAll(playableResults);
    }

    _pageList = playableResults;
    _currentPage = page;

    // 判断是否还有更多数据
    _hasMore = results.isNotEmpty && results.length >= 20; // 假设每页20条数据
  }

  /// 处理高亮文本
  /// 迁移自原始项目的 configHtmlDataAnalysis 方法
  Future<MusicItemModel> _processHighlightText(MusicItemModel item) async {
    // 这里可以根据需要处理高亮文本
    // 由于新的架构中，高亮文本处理可能在UI层进行
    // 暂时返回原始item，后续可以扩展
    return item;
  }

  /// 配置HTML数据中的高亮文本
  /// 迁移自原始项目的 configHtmlDataAnalysis 方法
  List<TextSpan> configHtmlDataAnalysis({
    required String htmlStr,
    required Color normalColor,
    Color primaryColor = const Color.fromRGBO(50, 240, 140, 1),
    bool disabled = false,
    double fontSize = 14,
  }) {
    List<TextSpan> textSpans = [];
    List<String> parts = htmlStr.split("<span class=\"c_tx_highlight\">");

    if (parts.length >= 2) {
      for (int i = 0; i < parts.length; i++) {
        String part = parts[i];
        List<String> spanParts = part.split("</span>");

        if (spanParts.length == 2) {
          // 高亮部分
          textSpans.add(TextSpan(
            text: spanParts[0],
            style: TextStyle(
              color: disabled ? normalColor : primaryColor,
              fontSize: fontSize,
              fontWeight: FontWeight.w500,
            ),
          ));
          // 普通部分
          textSpans.add(TextSpan(
            text: spanParts[1],
            style: TextStyle(
              color: normalColor,
              fontSize: fontSize,
              fontWeight: FontWeight.w500,
            ),
          ));
        } else {
          // 普通文本
          textSpans.add(TextSpan(
            text: spanParts[0],
            style: TextStyle(
              color: normalColor,
              fontSize: fontSize,
              fontWeight: FontWeight.w500,
            ),
          ));
        }
      }
    } else {
      // 没有高亮标签，直接添加普通文本
      textSpans.add(TextSpan(
        text: parts[0],
        style: TextStyle(
          color: normalColor,
          fontSize: fontSize,
          fontWeight: FontWeight.w500,
        ),
      ));
    }

    return textSpans;
  }

  /// 更新页面状态
  void _updatePageState() {
    if (_searchList.isEmpty) {
      setEmpty();
    } else {
      setSuccess();
    }
  }

  /// 加载搜索历史
  Future<void> _loadHistoryItems() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final jsonString = prefs.getString('music_search_history');

      if (jsonString != null) {
        final List<dynamic> jsonList = jsonDecode(jsonString);
        _historyItems = jsonList
            .map((item) => SearchItem.fromJson(item as Map<String, dynamic>))
            .toList();

        debugPrint('📚 加载搜索历史: ${_historyItems.length} 条记录');
        notifyListeners();
      }
    } catch (error, stackTrace) {
      debugPrint('⚠️ 加载搜索历史失败: $error');
      ErrorHandler.handleError(error, stackTrace);
    }
  }

  /// 保存搜索历史
  Future<void> _saveSearchHistory(SearchItem item) async {
    try {
      // 移除重复的搜索记录
      _historyItems.removeWhere((historyItem) => historyItem.text == item.text);

      // 添加新的搜索记录到第一位
      _historyItems.insert(0, item);

      // 限制历史记录数量（最多保存20条）
      if (_historyItems.length > 20) {
        _historyItems = _historyItems.take(20).toList();
      }

      // 转换为JSON并保存到本地
      final jsonList = _historyItems.map((item) => item.toJson()).toList();
      final jsonString = jsonEncode(jsonList);

      final prefs = await SharedPreferences.getInstance();
      await prefs.setString('music_search_history', jsonString);

      debugPrint('💾 保存搜索历史: ${item.text}');
      notifyListeners();
    } catch (error, stackTrace) {
      debugPrint('⚠️ 保存搜索历史失败: $error');
      ErrorHandler.handleError(error, stackTrace);
    }
  }

  /// 清空搜索历史
  Future<void> clearSearchHistory() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.remove('music_search_history');

      _historyItems.clear();
      debugPrint('🗑️ 清空搜索历史');
      notifyListeners();
    } catch (error, stackTrace) {
      debugPrint('⚠️ 清空搜索历史失败: $error');
      ErrorHandler.handleError(error, stackTrace);
    }
  }

  /// 删除单个搜索历史项
  Future<void> removeSearchHistoryItem(SearchItem item) async {
    try {
      _historyItems.remove(item);

      // 更新本地存储
      final jsonList = _historyItems.map((item) => item.toJson()).toList();
      final jsonString = jsonEncode(jsonList);

      final prefs = await SharedPreferences.getInstance();
      await prefs.setString('music_search_history', jsonString);

      debugPrint('🗑️ 删除搜索历史: ${item.text}');
      notifyListeners();
    } catch (error, stackTrace) {
      debugPrint('⚠️ 删除搜索历史失败: $error');
      ErrorHandler.handleError(error, stackTrace);
    }
  }

  /// 设置热门搜索项
  void setHotItems(List<SearchItem> items) {
    _hotItems = List.from(items);
    notifyListeners();
  }

  /// 添加热门搜索项
  void addHotItem(SearchItem item) {
    if (!_hotItems.contains(item)) {
      _hotItems.add(item);
      notifyListeners();
    }
  }

  /// 清空搜索结果
  void clearSearchResults() {
    _searchList.clear();
    _searchCanPlayList.clear();
    _pageList.clear();
    _currentQuery = '';
    _currentPage = 1;
    _hasMore = true;
    setState(PageState.idle);

    debugPrint('🧹 清空搜索结果');
  }

  /// 获取搜索建议
  /// 基于搜索历史提供搜索建议
  List<SearchItem> getSearchSuggestions(String query) {
    if (query.trim().isEmpty) {
      return [];
    }

    final suggestions = _historyItems
        .where((item) => item.text.toLowerCase().contains(query.toLowerCase()))
        .take(5)
        .toList();

    return suggestions;
  }

  /// 检查是否可以加载更多
  bool get canLoadMore =>
      _hasMore && state != PageState.loading && _currentQuery.isNotEmpty;

  /// 获取当前搜索状态描述
  String get searchStatusText {
    switch (state) {
      case PageState.loading:
        return _currentPage == 1 ? '搜索中...' : '加载更多...';
      case PageState.empty:
        return '未找到相关音乐';
      case PageState.error:
        return errorMessage ?? '搜索失败';
      case PageState.success:
        return '找到 ${_searchList.length} 首音乐';
      case PageState.noMore:
        return '没有更多结果了';
      default:
        return '';
    }
  }

  @override
  void dispose() {
    debugPrint('🔄 MusicSearchViewModel 销毁');
    super.dispose();
  }
}
